﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    private Transform _player;
    // public BoxCollider2D 
    // Start is called before the first frame update
    // 本身的刚体
    private BoxCollider2D _collider2D;
    private Rigidbody2D _rigidbody2D;
    // 动画
    private Animator _ani;
    private Vector3 _position;
    // 两步移动一次的参数
    private bool _isMove = true;
    // 控制速度的
    private float _smoothing;
    private float _restTime;
    private void Awake() {
        _player = GameObject.FindGameObjectWithTag("Player").transform;
        _collider2D = GetComponent<BoxCollider2D>();
        _rigidbody2D = GetComponent<Rigidbody2D>();
        _ani = GetComponent<Animator>();
        _position = transform.position;
        _smoothing = _player.GetComponent<Palyer>().smoothing;
        _restTime = _player.GetComponent<Palyer>().restTime;

        Director.Singles.Enemys.Add(this);
    }
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
        if (transform.position.Equals(_position)) {
            _restTime = 0;
        } else {
            _restTime += _smoothing * Time.deltaTime;
            _rigidbody2D.MovePosition(Vector3.Lerp(transform.position, _position, _restTime));
        }  
    }
    // 怪物移动
    public void move() {
        float x = 0, y = 0;
        Vector2 offset = _player.GetComponent<Palyer>().targetPos - new Vector2(_position.x, _position.y);
        // Debug.Log(offset.magnitude);
        if (offset.magnitude < 1.1) {
            _ani.SetTrigger("Attack");
            
            _player.gameObject.SendMessage("PlayerAttacked");
        } else {
            
            if (_isMove) {
                _isMove = false;
                return;
            }
            
            _isMove = true;
            if (Mathf.Abs(offset.x) >= Mathf.Abs(offset.y)) {
                
                if (offset.x < 0) {
                    x = -1;
                } else {
                    x = 1;
                }
            } else {
                if (offset.y < 0) {
                    y = -1;
                } else {
                    y = 1;
             
                }
            } 
            _collider2D.enabled = false;
            RaycastHit2D hit = Physics2D.Linecast(_position, _position + new Vector3(x, y, 0));
            _collider2D.enabled = true;
            if (hit.transform == null || hit.collider.tag == "Food" || hit.collider.tag == "Soda") {
                _position += new Vector3(x, y, 0);
            }
            
        }    
    }
}
